<?php

namespace App\Core\Event;

use App\Constants\AppInfo;
use App\Entities\HllEvent;
use App\Loggers\MallLogger;
use App\Models\Table\HllEventTable;
use App\Services\AppErrorService;
use Illuminate\Console\Command;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Process\Process;
use Symfony\Contracts\Cache\ItemInterface;

class HllEventReportCommand extends Command
{
    protected $signature = 'hllevent:report {pid?}
                            {--signal=-2 : The signal you want send}';

    private $startTime;

    private $endTime;

    public function handle()
    {
        $totalRs = $this->findEvevntByStatus();
        $total = 0;
        if ($totalRs) {
            $total = $totalRs['nums'];
        }
        $partSuccess = $this->findEvevntByStatus(HllEvent::ESTATUS_PARTIAL_SUCCESS, true);
        $fail = $this->findEvevntByStatus(HllEvent::ESTATUS_FAIL, true);
        $waitResult = $this->findEvevntByStatus(HllEvent::ESTATUS_WAIT,true);
        $appErrorService = new AppErrorService();
        $message = $this->conversionLarkMessageBody($total,[
            'part'=>$partSuccess,
            'fail'=>$fail,
            'wait'=>$waitResult
        ]);
        $appErrorService->baseSendLark($message);
    }

    private function findEvevntByStatus($status = null, $group = null)
    {
        $hllEventTable = new HllEventTable();
        $todayBeginTime = (new \DateTime('-1 day'))->format('Y-m-d 00:00:00');
        $this->startTime = $todayBeginTime;
        $todayEndTime = (new \DateTime('-1 day'))->format('Y-m-d 23:59:59');
        $this->endTime = $todayEndTime;
        $select = ['nums' => 'count(*)'];
        if ($group) {
            $select = ['nums' => 'count(*)', 'action'];
        }
        $query = $hllEventTable->getQueryBuilder()->select($select)->where(
            [
                'created_at >=' => $todayBeginTime,
                'created_at <=' => $todayEndTime
            ]
        );
        if ($status) {
            $query->where(['estatus' => $status]);
        }
        if ($group) {
            $result = $query->group('action')->all();
        } else {
            $result = $query->first();
        }
        return $result;
    }

    /**
     * @param $total
     * @param array{fail:array,part:array,wait:array} $result
     * @return array
     */
    public function conversionLarkMessageBody($total, $result)
    {
        $env = HLL_ENV;
        $time = $this->startTime.'~'.$this->endTime;
        /** @var MallLogger $logger */
        $logger = app('logger');
        $title = "[{$env}] 事件消费报告";
        $body = [
            "config" => ["wide_screen_mode" => true],
            "elements" =>
                [
                    [
                        "fields" =>
                            [
                                [
                                    "is_short" => true,
                                    "text" => ["content" => "**时间**\n{$time}", "tag" => "lark_md"]
                                ],
                                ["is_short" => true, "text" => ["content" => "**环境**\n{$env}", "tag" => "lark_md"]]
                            ],
                        "tag" => "div"
                    ],
                    [
                        "fields" =>
                            [
                                [
                                    "is_short" => true,
                                    "text" => ["content" => "**总量**\n{$total}", "tag" => "lark_md"]
                                ],
                            ],
                        "tag" => "div"
                    ],
                    ["tag" => "hr"],
                ], "header" =>
                [
                    "template" => "red",
                    "title" =>
                        ["content" => "{$title}", "tag" => "plain_text"]
                ]
        ];
        $partText = '';
        $partSuccess = $result['part'];
        foreach ($partSuccess as $item) {
            $partText .= " ".$item['action'] . ' ' . $item['nums'];
        }
        $failText = '';
        $fail = $result['fail'];
        foreach ($fail as $item) {
            $failText .= " ".$item['action'] . ' ' . $item['nums'];
        }
        $waitText = '';
        $wait = $result['wait'];
        foreach ($wait as $item) {
            $waitText .= " ".$item['action'] . ' ' . $item['nums'];
        }
        $fileds = [];
        $fileds[] = [
            "is_short" => true,
            "text" => ["content" => "**部分成功 **\n{$partText}", "tag" => "lark_md"]
        ];
        $fileds[] = [
            "is_short" => true,
            "text" => ["content" => "**失败 **\n{$failText}", "tag" => "lark_md"]
        ];
        $fileds[] = [
            "is_short" => true,
            "text" => ["content" => "**待处理 **\n{$waitText}", "tag" => "lark_md"]
        ];

        $body['elements'][] = [
            'fields' => $fileds,
            "tag" => "div"
        ];
        if (!HLL_IS_DEV) {
            $body['elements'][] = [
                "tag" => "div",
                "text" => [
                    "content" => "<at id=all>所有人<at>", "tag" => "lark_md"
                ]
            ];
        }
        return $body;
    }


}